<?php
/**
 * Created by PhpStorm.
 * User: chenzhitao
 * Date: 2018/4/27
 * Time: 下午10:03
 */

namespace App\Busi\Modules\Resource;


use App\Busi\Modules\BaseBusi;
use App\Http\Requests\IndexNewsRo;
use App\Models\News;
use Illuminate\Support\Facades\Cache;

class IndexNewsBusi extends BaseBusi
{
    public function handle(IndexNewsRo $ro){
        return $this->getIndexNewsList();
    }
    function getIndexNewsList(){

//        $mem_key = "indexnews_list_key_";
//        if( $data = Cache::get($mem_key) ){
//            $data = json_decode($data, true);
//            return $data;
//        }

        $where = [
            ['flag',"=",1]
        ];
        $fields = ['id',"title","poster","created_at"];
        $data = News::where($where)->select($fields)->limit(10)->orderBy(\DB::raw('RAND()'))->get();

        $news_list = [];


        foreach ($data as $item){

            $news_item = [];
            $news_item["id"] = $item["id"];
            $news_item["title"] = $item["title"];
            $news_item["tag"] = $this->getTags($item->tags);
            $news_item["create_time"] = substr($item["created_at"],5,5);

            $news_item["poster"] = config('admin.upload.host').$item['poster'];
            array_push($news_list,$news_item);
        }
        $rand_num = count($news_list) > 4 ? 4:count($news_list);
        $rand_keys = array_rand($news_list,$rand_num);
        $banner_list = [];
        //在新闻列表中随机选出四个banner图
        foreach ($rand_keys as $key){
            $banner_item = [];
            $banner_item['id'] = $news_list[$key]['id'];
            $banner_item['title'] = $news_list[$key]['title'];
            $banner_item['poster'] = $news_list[$key]['poster'];
            array_push($banner_list,$banner_item);
        }


        
        $ret = [
            "left_poster"=>$banner_list,
            "list"=>$news_list
        ];


//        Cache::put($mem_key, json_encode($ret), 60*12);

        return $ret;
    }
    function getTags($tags){
        $tag_list = "";
        if($tags){
            foreach ( $tags as $tag){
                $tag_list.=$tag['name'];
            }
        }
        return $tag_list;
    }
}